package org.travel.travel2gether.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.travel.travel2gether.exception.FacebookAuthenticationException;
import org.travel.travel2gether.service.FacebookService;

@Controller
public class FacebookController {
	
	private final Logger logger = LoggerFactory.getLogger(FacebookController.class);
	
	@Autowired
	private FacebookService fbService;
	
	@RequestMapping(value = "/facebookLogin")
	public void getFacebookLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String url = fbService.getLoginRedirectURL();
		response.sendRedirect(url);
	}
	
	@RequestMapping(value = "/facebookAuthentication", method = RequestMethod.GET)
	public String facebookAuthentication(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException, FacebookAuthenticationException {
		String code = request.getParameter("code");
		if (code != null && !code.isEmpty()) {
			fbService.authenticate(code);
		} else {
			throw new FacebookAuthenticationException();
		}
		return "redirect:/";
	}
	
	@ExceptionHandler({ClientProtocolException.class, IOException.class, FacebookAuthenticationException.class})
	public String errorRedirect() {
		logger.error("Facebook login error");
		return "error";
	}
}
